import Box from "./Box";
import { LanguageManager } from "./language/LanguageManager";
import RESSpriteFrame from "./RESSpriteFrame";
import Anim from "./utils/Anim";
import EffectUtils from "./utils/EffectUtils";
import MoneyChange from "./utils/MoneyChange";
import Utils from "./utils/Utils";


const { ccclass, property } = cc._decorator;

@ccclass
export default class GameUI extends cc.Component {
    @property(cc.Sprite)
    private scratchSprite: cc.Sprite = null
    @property(cc.SpriteFrame)
    private scratchSpriteArr: cc.SpriteFrame[] = []
    @property(cc.Node)
    private flyBoxMask:cc.Node = null
    @property(cc.Prefab)
    private BoxTail:cc.Prefab = null;
    @property(cc.Node)
    private scratchNode: cc.Node = null
    @property(cc.Node)
    private TopBoxArr: cc.Node[] = []
    @property(cc.Node)
    private boxArr: cc.Node[] = []
    @property(cc.Node)
    private coinNode: cc.Node = null
    @property(cc.Node)
    private boxPool: cc.Node = null
    @property(cc.Node)
    private boxTitleNode: cc.Node = null;
    @property(cc.Node)
    private topBg: cc.Node = null;
    @property(cc.Node)
    private topBox: cc.Node = null
    @property(cc.Node)
    private highBox: cc.Node = null
    @property(cc.Node)
    private hundredNode: cc.Node = null;
    @property(cc.Node)
    private horBg: cc.Node = null;
    @property(cc.Node)
    private resultBtn: cc.Node = null;
    @property(cc.Node)
    private resultTitle: cc.Node = null;
    @property(cc.Node)
    private moneyPar: cc.Node = null;
    @property(cc.Label)
    private moneyLabel: cc.Label = null;
    @property(cc.Node)
    private sySytem: cc.Node = null
    @property(cc.Node)
    private animFinger: cc.Node = null
    @property(cc.Node)
    private finger: cc.Node = null;
    @property(cc.Node)
    private maskBg: cc.Node = null
    @property(cc.Mask)
    private maskNode: cc.Mask = null
    @property(cc.Node)
    private zhezhao: cc.Node = null;
    @property(cc.Label)
    private tipLabel: cc.Label = null;
    @property(cc.Label)
    private tipLabel1: cc.Label = null;
    @property(cc.Node)
    private resultNode: cc.Node = null;
    @property(cc.Prefab)
    private moneyPrefab: cc.Prefab = null

    private canPlayMusic: boolean = false
    private moneyChange: MoneyChange = null;
    private isFirstClcik: boolean = true
    private allData: any = null
    private raduis: number = 67
    private amount: number = 0
    private bgmAudioFlag: boolean = true
    private allNum: number = null
    private clearId: number = null
    private originPosY: number = null
    protected start(): void {
        PlayerAdSdk.init();
        this.resize()
        let that = this;
        /**屏幕旋转尺寸改变 */
        cc.view.setResizeCallback(() => {
            that.resize();
        })
        this.animFinger.active = true
        this.finger.active = this.moneyPar.active = this.resultBtn.active = this.resultTitle.active = false
        cc.find('Canvas').on('touchstart', (e) => {
            this.canPlayMusic = true
            if (this.isFirstClcik) {
                this.scratchNode.stopAllActions()
                this.scratchNode.y = this.originPosY
                cc.director.getScene().getComponentsInChildren(cc.Widget).forEach(function (t) {
                    t.updateAlignment()
                });
                this.bgmAudioFlag && cc.audioEngine.play(RESSpriteFrame.instance.bgmAudioClip, false, 1)
                this.animFinger.active = false
                this.isFirstClcik = false
            }
        })
        this.flyBoxMask.active = false
        for(let i =0; i < this.boxArr.length;i++){
            this.boxArr[i].active = false
        }
        console.log('jayY',this.originPosY);
        this.originPosY = this.scratchNode.y
        this.moneyChange = new MoneyChange(this.moneyLabel, true, this.amount)
        this.moneyLabel.string = `${this.amount}.00`
        Utils.SetScale(this.moneyLabel.node, 1.1, 0.6, true)
        cc.tween(this.scratchNode)
            .repeatForever(
                cc.tween()
                    .to(0.3, { y: this.originPosY - 20 })
                    .to(0.3, { y: this.originPosY - 40 })
                    .to(0.3, { y: this.originPosY - 20 })
                    .to(0.3, { y: this.originPosY})
            ).start()
        this.resize()
        let ratio = cc.winSize.width / cc.winSize.height
        if (ratio < 0.55) {
            this.topBg.getComponent(cc.Widget).top = 20
            this.topBox.getComponent(cc.Widget).top = cc.winSize.height / 6
            this.topBox.scale = 1.15
            this.hundredNode.getComponent(cc.Widget).top = 480
        } else {
            this.topBg.getComponent(cc.Widget).top = -36
            this.topBox.getComponent(cc.Widget).top = 176
        }
        this.initData()
        this.allNum = this.allData.length
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartFunc, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveFunc, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEndFunc, this)
        this.boxPool.active = this.boxTitleNode.active = this.resultNode.active = false
        this.amount = LanguageManager.instance.formatUnit(this.amount)
        let unit = LanguageManager.instance.getText(10001)
    }
    private initData() {
        let rows = Math.floor(this.maskBg.height / (this.raduis * 2))
        let cols = Math.floor(this.maskBg.width / (this.raduis * 2))
        this.allData = []
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                this.allData.push({ "x": j, "y": i })
            }
        }
    }
    private reomveData(pos: any) {
        let x = Math.floor((pos.x + this.maskBg.width / 2) / (this.raduis * 2))
        let y = Math.floor((pos.y + this.maskBg.height / 2) / (this.raduis * 2))
        for (let i = 0; i < this.allData.length; i++) {
            if (this.allData[i].x == x && this.allData[i].y == y) {
                this.allData.splice(i, 1)
            }
        }
    }
    private touchStartFunc(e) {
        this.scratchSprite.spriteFrame =  this.scratchSpriteArr[0]
        this.clearId = cc.audioEngine.play(RESSpriteFrame.instance.clearAudioClip, true, 1)
        this.sySytem.active = true
        this.finger.active = true
        let pos = e.getLocation()
        pos = this.finger.parent.convertToNodeSpaceAR(pos)
        this.finger.x = pos.x
        this.finger.y = pos.y
    }
    //刮动作事件
    private touchMoveFunc(e) {
        let pos = this.getPos(e)
        let delta = e.getDelta()
        this.finger.x += delta.x
        this.finger.y += delta.y
        // let pos1 = e.getLocation()
        // pos1 = this.finger.parent.convertToNodeSpaceAR(pos1)
        // this.finger.setPosition(pos1)
        this.clearFunc(pos)
        this.reomveData(pos)
    }
    private touchEndFunc() {
        this.scratchSprite.spriteFrame =  this.scratchSpriteArr[1]
        cc.audioEngine.pause(this.clearId)
        this.sySytem.active = false
        let isFinish = this.allData.length / this.allNum < 0.5 ? true : false
        if (isFinish) {
            this.highBox.active = true
            this.maskNode.node.active = this.finger.active = false
            let pos: cc.Vec2 = this.moneyLabel.node.parent.convertToWorldSpaceAR(new cc.Vec2(this.moneyLabel.node.x, this.moneyLabel.node.y))
            pos = this.node.convertToNodeSpaceAR(pos)
            Anim.ins().ShowFlyAni(this.moneyPrefab, this.node, 10, pos, () => {
                console.log(111);
            }, this, this.maskNode.node.position)
            this.amount = LanguageManager.instance.formatUnit(500)
            setTimeout(() => {
                let id = cc.audioEngine.play(RESSpriteFrame.instance.numberAddAudioClip, false, 3)
                this.zhezhao.active = true
                this.moneyChange.play(this.amount, 0.8, () => {
                    cc.audioEngine.pause(id)
                    let pos = null
                    let tail = null
                    this.flyBoxMask.active = true
                    for (let i = 0; i < this.boxArr.length; i++) {
                        this.boxArr[i].active = true
                        this.boxArr[i].scale = 0.45
                        tail = cc.instantiate(this.BoxTail).getComponent(Box)
                        this.boxArr[i].addChild(tail.node)
                        pos = this.TopBoxArr[i].parent.convertToWorldSpaceAR(this.TopBoxArr[i].position)
                        pos = this.boxArr[i].parent.convertToNodeSpaceAR(pos)
                        cc.tween(this.boxArr[i])
                            .to(0.2,{y:this.boxArr[i].y - 20})
                            .to(1.5, { position: pos, scale: 0.5, opacity: 200 }, { easing: 'quadOut' })
                            .call(() => {
                                this.boxArr[i].active = false
                                if (i == this.boxArr.length - 1) {
                                    Utils.showUI(this.resultNode, RESSpriteFrame.instance.comeOutAudioClip, 0.3, this.canPlayMusic, 1.1, 1, () => {
                                        cc.audioEngine.play(RESSpriteFrame.instance.cherrUpAudioClip, false, 1)
                                        this.boxPool.active = true
                                        let boxAnimNode = this.boxPool.children[4].getComponent(cc.Animation)
                                        boxAnimNode.on('finished', () => {
                                            this.boxTitleNode.active = this.coinNode.active = true
                                            this.moneyPar.active = true
                                            for (let i = 0; i < this.boxPool.children.length; i++) {
                                                if (this.boxPool.children[i].name = 'coinpar') {
                                                    this.boxPool.children[i].active = true
                                                }
                                                if (this.boxPool.children[i].name = 'light') {
                                                    // this.boxPool.children[i].getComponent(cc.Animation).play('btn')
                                                    setTimeout(() => {
                                                        Utils.SetScale(this.boxPool.children[i], 1.2, 0.3, true)
                                                    }, 500);
                                                    setTimeout(() => {
                                                        Utils.showUI(this.resultTitle,null,0.1,false,1.2,1)
                                                        Utils.showUI(this.resultBtn,null,0.1,false,1.2,1)
                                                    }, 1000);
                                                }
                                            }
                                        })

                                    })
                                }
                            })
                            .start()
                    }
                }, this)
            }, 800);
        }
    }
    private getPos(e) {
        return this.maskBg.convertToNodeSpaceAR(e.getLocation())
    }
    private clearFunc(pos) {
        let graphics = this.maskNode._graphics
        // graphics.fillRect(pos.x,pos.y,60,60)
        graphics.circle(pos.x, pos.y, this.raduis)
        graphics.fill()
    }
    private getRandomInt(min: number, max: number) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    private resize() {
        const canvasValue: any = cc.Canvas.instance;
        let frameSize = cc.view.getFrameSize();
        let isVerTical = cc.winSize.height > cc.winSize.width
        this.horBg.active = !isVerTical
        // cc.loader.loadRes(`pay/money/${cc.sys.language}`, cc.SpriteFrame,(err,res)=>{
        //     this.moneyPar.getComponent(cc.ParticleSystem).spriteFrame = res
        // }); 
        if (isVerTical) {//竖屏
            if (cc.winSize.width / cc.winSize.height > 0.7) {
                cc.Canvas.instance.fitHeight = true;
                cc.Canvas.instance.fitWidth = false;
            } else {
                cc.Canvas.instance.fitHeight = false;
                cc.Canvas.instance.fitWidth = true;
            }
        } else {
            cc.Canvas.instance.fitHeight = true;
            cc.Canvas.instance.fitWidth = false;
        }
        cc.director.getScene().getComponentsInChildren(cc.Widget).forEach(function (t) {
            t.updateAlignment()
        });
    }
    private cashoutFunc() {
        console.log('跳转');
        cc.audioEngine.play(RESSpriteFrame.instance.clickAudioClip, false, 1)
        PlayerAdSdk.gameEnd()
        PlayerAdSdk.jumpStore()
    }
}   
